/******************************************************************************
 * Copyright (C) 2016  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "node/system/thread_POSIX.h"
#include <assert.h>
#include "node/system/runnable.h"

namespace node {
	namespace system {

	thread_impl::thread_impl(void)
        : _id(0)
        , _runnable(0)
    {

    }
    thread_impl::~thread_impl(void)
    {

    }

    bool thread_impl::start_impl(runnable* runnable)
    {
        assert(_id == 0L);
        _runnable = runnable;
        if (pthread_create(&_id, 0, thread_impl::proc, this) == 0) {
        	return true;
        }
        _id = 0L;
        return false;
    }
    void thread_impl::join_impl(void)
    {
        assert(_id != 0L);
        if (_id != 0L) {
            pthread_join(_id, 0);
        }
    }
    bool thread_impl::joinable_impl(void)
    {
        return _id != 0L;
    }
    bool thread_impl::set_priority_impl(int priority)
    {
#if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
    	int policy;
    	pthread_attr_t thread_attr;
    	struct sched_param thread_param;
    	if (pthread_attr_getschedpolicy(&thread_attr, &policy) != 0) {
    		return false;
    	}
    	if (pthread_attr_getschedparam(&thread_attr, &thread_param) != 0) {
    		return false;
    	}
    	int priority_min = sched_get_priority_min(policy);
    	int priority_max = sched_get_priority_max(policy);
    	int priority_step = (priority_max - priority_min) / 5;

    	thread_param.sched_priority = priority_min + priority_step * priority;
    	if (pthread_attr_setschedparam(&thread_attr, &thread_param) != 0) {
    		return false;
    	}
#endif
        return true;
    }
    void* thread_impl::proc(void *argument)
    {
        assert(argument);
        thread_impl* impl = static_cast<thread_impl*>(argument);
        impl->_runnable->run();
        return NULL;
    }

}}